#include "StdAfx.h"
#include "FileDeviceHandleRegular.h"

namespace ja2{ namespace vfs
{
	FileDeviceHandleRegular::FileDeviceHandleRegular(boost::filesystem::path const &FilePath)
		: FileDeviceHandle(FilePath, FilePath.string())
	{
	}

	FileDeviceHandleRegular::FileDeviceHandleRegular(boost::filesystem::path const &FilePath, std::ios_base::openmode Mode)
		: FileDeviceHandle(FilePath, FilePath.string()), m_Stream(FilePath.string(), Mode)
	{
	}

	std::streamsize FileDeviceHandleRegular::read(char *Buffer, std::streamsize Size)
	{
		std::streamsize ret = Size;
		// Error while reading
		if(!m_Stream.read(Buffer, Size))
		{
			// We haven't read anything
			if((ret = m_Stream.gcount()) < 1)
			{
				// End of file
				if(m_Stream.eof())
					ret = -1;
				// Unknown error
				else
					JA2_ASSERT(false);
			}
		}

		return ret;
	}
	
	std::streamsize FileDeviceHandleRegular::write(const char* /*Buffer*/, std::streamsize /*Size*/)
	{
		throw UnimplementedException(std::string(__FUNC__));
	}
	
	boost::iostreams::stream_offset FileDeviceHandleRegular::seek(boost::iostreams::stream_offset /*Offset*/, std::ios_base::seekdir /*Direction*/)
	{
		throw UnimplementedException(__FUNC__);
	}

	void FileDeviceHandleRegular::open(std::ios_base::openmode Mode)
	{
		m_Stream.open(get_real_name().string(), Mode);
	}
	
	bool FileDeviceHandleRegular::is_open() const
	{
		return m_Stream.is_open();
	}
	
	void FileDeviceHandleRegular::close()
	{
		m_Stream.close();
	}
} /*vfs*/} /*ja2*/